/**
 * @Author: pandali
 * @Date: 2018-05-21 20:38:43
 * @Last Modified by: pandali
 * @Last Modified time: 2018-06-22 13:58:33
 * 微信JSSDK设置 wx config.
 */
import Service from './business/service/base.service'
import { config, storage, sign, utils } from './business/index'
import wx from 'weixin-js-sdk'

export default class WxJsSDK extends Service {
  constructor () {
    // 初始化行为
    super()
    this.token = '214e1ba0-ce80-42d5-bda8-8e97c8dd7a2c'
    this.baseUrl = this.__getBaseUrl()
    this.appid = this.__getAppId()[config.env]
    this.wxSystemApi = wx
  }

  setup () {
    return super.setup()
    // 启动行为
  }

  __getBaseUrl () {
    const url = {
      dev: '//api-dev.boqii.com/',
      gqc: '//api-dev.boqii.com/',
      prd: '//api.boqii.com/'
    }
    return url
  }

  __getAppId () {
    const appid = {
      dev: 'wx841edaddbf22259c',
      gqc: 'wx841edaddbf22259c',
      prd: 'wxb5d575673dbec527'
    }
    return appid
  }

  __getConfigParams (url = 'http://m.boqii.com') {
    url = url.split('#')[0] // `${location.origin}${location.pathname}`

    const data = { url }
    const Sign = sign.creator(data)
    const Authorization = ''

    return this.request(
      'weixin/js_config',
      'GET',
      data,
      {
        Sign,
        Authorization,
        'Vary-Client': 'web'
      }
    )
  }

  config(url) {
    const promise = this.__getConfigParams(url)
    return promise.then(res => {
      wx.config(res.ResponseData)
      return wx
    })
  }

  /**
   * 微信分享.
   * @param {string} title 分享标题
   * @param {string} link 分享链接
   * @param {string} imgUrl 分享图片地址
   * @param {string} desc 分享朋友圈描述
   * @param {object} success
   * @param {object} cancel
   */
  onMenuShareMessage (title, link, imgUrl, desc, success, cancel) {
    wx.ready(function () {
      // 分享朋友圈
      wx.onMenuShareTimeline({
        title,
        link,
        imgUrl,
        success,
        cancel
      })
      // 分享给朋友
      wx.onMenuShareAppMessage({
        title,
        desc,
        link,
        imgUrl,
        success,
        cancel
      })
    })
  }
  /**
   * 网页授权登录.
   */
  authorizationLogin() {
    const returnUrl = `${location.origin}${location.pathname}`
    const loginUrl = `${location.protocol}${this._getBaseUrl()[config.env]}`
    const openid = storage.getItemSync('openid')
    const wechatAuthorizeParams = utils.params({
      appid: this.appid,
      redirect_uri: `${loginUrl}weixin/record_info?openid=${openid}`,
      response_type: 'code',
      scope: 'snsapi_userinfo',
      state: returnUrl
    })

    const authorizeUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?' + wechatAuthorizeParams + '#wechat_redirect'

    window.location.href = authorizeUrl
  }

  /**
   * 检查微信端是否登录
   */
  checkAuthStatus() {
    return new Promise(function (resolve, reject) {
      const wxData = utils.queryString('data')
      const openid = storage.getItemSync('openid')
      if (!openid) {
        if (wxData && wxData !== undefined) {
          const wxDataToJson = JSON.parse(decodeURIComponent(wxData)) || {}
          if (wxDataToJson.ResponseData && wxDataToJson.ResponseData.openid) {
            storage.setItemSync('openid', wxDataToJson.ResponseData.openid)
            resolve(wxDataToJson.ResponseData)
          } else {
            reject(new Error('微信授权失败'))
          }
        } else {
          setTimeout(function() {
            reject(new Error('用户未授权'))
          }, 2000)
        }
      } else {
        resolve(wxData)
      }
    })
  }
}
